package com.zheng.oa.admin.controller.hr;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zheng.common.base.BaseController;
import com.zheng.common.util.Pagination;
import com.zheng.common.util.PoiUtil;
import com.zheng.common.validator.ByteValidator;
import com.zheng.common.validator.LengthValidator;
import com.zheng.hr.dao.model.*;
import com.zheng.hr.rpc.api.*;
import com.zheng.oa.common.constant.OaResult;
import com.zheng.oa.common.constant.OaResultConstant;
import com.zheng.oa.common.exception.OaException;
import com.zheng.upms.dao.model.UpmsOrganization;
import com.zheng.upms.dao.model.UpmsUser;
import com.zheng.upms.rpc.api.UpmsApiService;
import com.zheng.upms.rpc.api.UpmsOrganizationService;
import com.zheng.upms.rpc.api.UpmsUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: xinqi
 * Date: 2018/1/10
 * Time: 14:48
 */
@Controller
@RequestMapping("/oa/hr/personalRecords")
public class HrPersonalRecordsController extends BaseController {
    @Autowired
    private HrPersonalRecordsService personalRecordsService;
    @Autowired
    private HrPositionService positionService;
    @Autowired
    private HrPersonalExperienceService experienceService;
    @Autowired
    private UpmsOrganizationService organizationService;
    @Autowired
    private HrPersonalContractRecordsService contractRecordsService;
    @Autowired
    private HrPersonalContractService contractService;
    @Autowired
    private UpmsApiService apiService;
    @Autowired
    private UpmsUserService userService;

    @ApiOperation(value = "人事档案管理首页")
    @RequiresPermissions("oa:hr:personalRecords:read")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model) {
        List<HrPosition> positions = positionService.selectList(null);
        model.addAttribute("positionList", JSON.toJSON(positions));
        List<UpmsOrganization> upmsOrganizations = organizationService.selectList(null);
        model.addAttribute("organizationList", JSON.toJSON(upmsOrganizations));
        return "/manage/hr/personalRecords/index.jsp";
    }

    @ApiOperation(value = "岗位列表")
    @RequiresPermissions("oa:hr:personalRecords:read")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Object list(@RequestParam(required = false, defaultValue = "1", value = "pageNumber") int pageNumber,
                       @RequestParam(required = false, defaultValue = "10", value = "pageSize") int pageSize,
                       @RequestParam(required = false, value = "sortName") String sortName,
                       @RequestParam(required = false, value = "sortOrder") String sortOrder,
                       HrPersonalRecords personalRecords) {
        personalRecords.setPagination(new Pagination(pageNumber, pageSize, sortOrder, sortName));
        List<Map<String, Object>> records = personalRecordsService.selectPersonalRecordsPage(personalRecords);
        int total = personalRecordsService.selectPersonalRecordsCount(personalRecords);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", records);
        result.put("total", total);
        return result;
    }

    @RequiresPermissions("oa:hr:personalRecords:create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(Model model) {
        return "/manage/hr/personalRecords/create.jsp";
    }

    @RequiresPermissions("oa:hr:personalRecords:create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Object create(@RequestBody JSONObject param) {
        HrPersonalRecords personalRecord = param.toJavaObject(HrPersonalRecords.class);
        List<HrPersonalExperience> experiences = param.getJSONArray("experiences").toJavaList(HrPersonalExperience.class);
        ComplexResult result = FluentValidator.checkAll()
                .on(personalRecord.getRealname(), new LengthValidator(0, 20, "姓名"))
                .on(personalRecord.getJobNumber(), new LengthValidator(0, 20, "工号"))
                .on(personalRecord.getJobNumber(), new ByteValidator("工号"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new OaResult(OaResultConstant.FAILED, result.getErrors().get(0).getErrorMsg());
        }
        try {
            personalRecordsService.insertPersonalRecords(personalRecord, experiences);
        } catch (OaException e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }

    @ApiOperation(value = "修改人事档案")
    @RequiresPermissions("oa:hr:personalRecords:update")
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String update(Model model, Integer id) {
        HrPersonalRecords personalRecords = personalRecordsService.selectById(id);
        EntityWrapper<HrPersonalExperience> experienceEntityWrapper = new EntityWrapper<>();
        experienceEntityWrapper.where("personal_id=" + personalRecords.getId());
        List<HrPersonalExperience> experiences = experienceService.selectList(experienceEntityWrapper);
        if (experiences.size() < 1) {
            experiences.add(new HrPersonalExperience());
        }
        model.addAttribute("personalRecords", personalRecords);
        model.addAttribute("experiences", experiences);

        Integer positionId = personalRecords.getPositionId();
        HrPosition position = new HrPosition();
        if (null != positionId) {
            position = positionService.selectById(positionId);
        } else {
            position.setName("未设置");
        }
        Integer organizationId = personalRecords.getOrganizationId();

        UpmsOrganization organization = new UpmsOrganization();
        if (null != organizationId) {
            organization = organizationService.selectById(organizationId);
        } else {
            organization.setName("未设置");
        }
        model.addAttribute("position", position);
        model.addAttribute("organization", organization);

        return "/manage/hr/personalRecords/update.jsp";
    }

    @ApiOperation(value = "修改人事档案")
    @RequiresPermissions("oa:hr:personalRecords:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object update(@RequestBody JSONObject param) {
        HrPersonalRecords personalRecord = param.toJavaObject(HrPersonalRecords.class);
        List<HrPersonalExperience> experiences = param.getJSONArray("experiences").toJavaList(HrPersonalExperience.class);
        ComplexResult result = FluentValidator.checkAll()
                .on(personalRecord.getRealname(), new LengthValidator(0, 20, "姓名"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new OaResult(OaResultConstant.FAILED, result.getErrors().get(0).getErrorMsg());
        }
        try {
            personalRecordsService.updatePersonalRecords(personalRecord, experiences);
        } catch (OaException e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }

    @ApiOperation(value = "导出人事档案信息")
    @RequiresPermissions("oa:hr:personalRecords:read")
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public Object export(Model model, HrPersonalRecords personalRecords) {
        model.addAttribute("searchParams", JSON.toJSON(personalRecords));
        return "/manage/hr/personalRecords/export.jsp";
    }


    @ApiOperation(value = "导出人事档案信息")
    @RequiresPermissions("oa:hr:personalRecords:read")
    @RequestMapping(value = "/export", method = RequestMethod.POST)
    public void export(HttpServletResponse response, String param) throws OaException {
        JSONObject jsonParam = JSONObject.parseObject(param);
        JSONArray entities = jsonParam.getJSONArray("entities");
        JSONObject searchParams = jsonParam.getJSONObject("searchParams");
        HrPersonalRecords personalRecords = searchParams.toJavaObject(HrPersonalRecords.class);
        List<Map<String, Object>> list = personalRecordsService.selectPersonalRecordsMaps(personalRecords);
        list = personalRecordsService.personalRecordsMapsTransformation(list);
        try {
            PoiUtil.export(response, list, entities, "人事档案信息", "人事档案信息");
        } catch (Exception e) {
            throw new OaException(e.getMessage());
        }
    }

    @ApiOperation(value = "查看人事信息")
    @RequiresPermissions("oa:hr:personalRecords:read")
    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public String view(Integer id, Model model) {
        HrPersonalRecords personalRecords = personalRecordsService.selectById(id);
        EntityWrapper<HrPersonalExperience> experienceEntityWrapper = new EntityWrapper<>();
        experienceEntityWrapper.where("personal_id=" + personalRecords.getId());
        List<HrPersonalExperience> experiences = experienceService.selectList(experienceEntityWrapper);
        if (experiences.size() < 1) {
            experiences.add(new HrPersonalExperience());
        }
        model.addAttribute("personalRecords", personalRecords);
        model.addAttribute("experiences", experiences);

        Integer positionId = personalRecords.getPositionId();
        HrPosition position = new HrPosition();
        if (null != positionId) {
            position = positionService.selectById(positionId);
        } else {
            position.setName("未设置");
        }
        Integer organizationId = personalRecords.getOrganizationId();

        UpmsOrganization organization = new UpmsOrganization();
        if (null != organizationId) {
            organization = organizationService.selectById(organizationId);
        } else {
            organization.setName("未设置");
        }
        model.addAttribute("position", position);
        model.addAttribute("organization", organization);

        EntityWrapper<HrPersonalContract> contractEntityWrapper = new EntityWrapper<>();
        contractEntityWrapper.where("personal_id=" + id);
        HrPersonalContract contract = contractService.selectOne(contractEntityWrapper);


        EntityWrapper<HrPersonalContractRecords> contractRecordsEntityWrapper = new EntityWrapper<>();
        contractRecordsEntityWrapper.where("personal_id=" + id);
        if (null != contract) {
            contractRecordsEntityWrapper.and().notIn("contract_id", contract.getId());
        }
        contractRecordsEntityWrapper.orderBy("ctime", false);
        List<HrPersonalContractRecords> contractRecordses = contractRecordsService.selectList(contractRecordsEntityWrapper);

        model.addAttribute("contract", contract);
        model.addAttribute("contractRecordses", contractRecordses);

        return "/manage/hr/personalRecords/view.jsp";
    }

    @RequestMapping(value = "/userInfo", method = RequestMethod.GET)
    public String userInfo(Model model) {
        UpmsUser upmsUser = apiService.selectUpmsUserByUsername(getUsername());
        Map<String, Object> personalRecords = personalRecordsService.getPersonalRecordsInfo(upmsUser.getUserId());
        model.addAttribute("personalRecords", personalRecords);
        model.addAttribute("user", upmsUser);
        return "/manage/hr/userInfo.jsp";
    }

    @RequestMapping(value = "/updateUserInfo", method = RequestMethod.POST)
    @ResponseBody
    public Object updateUserInfo(@RequestBody HrPersonalRecords personalRecord) {
        personalRecordsService.updateById(personalRecord);
        return new OaResult(OaResultConstant.SUCCESS, null);
    }
    @RequestMapping(value = "/synchronizationUserList", method = RequestMethod.GET)
    @ResponseBody
    public Object synchronizationUserList() {
        try {
//            weixinService.synchronizationUserList();
        } catch (Exception e) {
            return new OaResult(OaResultConstant.FAILED, null);
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }
}
